package logic

import (
	"context"
	"fmt"
	"user_center/models/cache"
	"user_center/models/mysql"

	"user_center/userrpc/internal/svc"
	"user_center/userrpc/userrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type UserRegisterLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUserRegisterLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserRegisterLogic {
	return &UserRegisterLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 用户注册登录
func (l *UserRegisterLogic) UserRegister(in *userrpc.UserRegisterRequest) (*userrpc.UserRegisterResponse, error) {
	// todo: add your logic here and delete this line
	var users mysql.User
	mysql.DB.Debug().Where("mobile = ?", in.Mobile).Find(&users)
	if users.ID == 0 {
		register := mysql.User{
			Mobile: in.Mobile,
		}
		mysql.DB.Debug().Create(&register)
	}

	sendSmsCode := cache.Rdb.Get(l.ctx, "sendSms"+in.Mobile).Val()
	if sendSmsCode != in.SendSmsCode {
		return nil, fmt.Errorf("验证码输入错误，请重新输入")
	}

	return &userrpc.UserRegisterResponse{
		Id: int64(users.ID),
	}, nil
}
